package net.apecloud.plugin;

import net.apecloud.plugin.util.ObfuscateUtil;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author YuanShuai[apeblog@163.com]
 */
@Mojo(name = "obfuscate-js", defaultPhase = LifecyclePhase.COMPILE)
public class JsObfuscateMojo extends AbstractMojo {

    @Parameter(defaultValue = "${project.basedir}/src/main/resources", property = "inputDirectory", required = true)
    private File inputDirectory;

    @Parameter(defaultValue = "${project.build.directory}/processed-resources", property = "outputDirectory", required = true)
    private File outputDirectory;

    public void execute() throws MojoExecutionException {
        getLog().info("Obfuscating JavaScript files");
        getLog().info("Input Directory: " + inputDirectory);
        getLog().info("Output Directory: " + outputDirectory);

        if (!inputDirectory.exists()) {
            throw new MojoExecutionException("Input directory does not exist: " + inputDirectory);
        }

        try (Stream<Path> paths = Files.walk(inputDirectory.toPath())) {
            List<Path> files = paths
                    .filter(path -> path.toString().endsWith(".js"))
                    .filter(Files::isRegularFile)
                    .collect(Collectors.toList());

            for (Path file : files) {
                getLog().info("Obfuscating file: " + file);

                // 读取文件内容
                String content = Files.readString(file);

                // 混淆JavaScript内容
                String obfuscatedContent = ObfuscateUtil.obfuscate(content);

                // 确定输出文件路径
                Path relativePath = inputDirectory.toPath().relativize(file);
                Path outputFile = outputDirectory.toPath().resolve(relativePath);

                // 如果目录不存在，创建目录
                Files.createDirectories(outputFile.getParent());

                // 将混淆后的内容写入输出文件
                Files.writeString(outputFile, obfuscatedContent);

                getLog().info("Obfuscated file written to: " + outputFile);
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Error obfuscating JavaScript files", e);
        }
    }
}
